<template>
  <div class="chat">
    <div class="head">
      <div v-if="!friendShow">房间号：{{ uuid }}</div>
      <div class="friend" v-if="friendShow">
        <img :src="friendImg" alt="" />
        {{ friendName }}
      </div>
    </div>
    <router-view></router-view>
    <div class="body">
      <div
        v-for="(item, index) in messageRecord"
        :key="index"
        :class="{ me: item.sender == 'me' }"
        class="message"
      >
        <img :src="item.imgUrl" alt="" />
        <div v-if="item.type == 'message'">{{ item.content }}</div>
        <img v-if="item.type == 'img'" :src="item.content" alt="" />
      </div>
    </div>
    <div class="bottom">
      <div class="input">
        <i class="el-icon-plus" @click="bottomBodyGoShow"></i>
        <el-input
          maxlength="1000"
          v-model="content"
          placeholder="消息内容"
        ></el-input>
        <el-button type="success" @click="sendMessage()">发送</el-button>
      </div>
      <div class="body" v-show="bottomBodyShow">
        <div>
          <i class="el-icon-picture" @click="choiceImg"></i>
        </div>
        <!-- <div>
          <i class="el-icon-phone" @click="goRedio"></i>
        </div> -->
      </div>
    </div>
    <input ref="filElem" type="file" class="upload-file" @change="getFile" />
    <div class="redio" v-if="redio">
      <router-view></router-view>
    </div>
  </div>
</template>

<script>
import Vue1 from "@/main";
import { v4 as uuidv4 } from "uuid";
export default {
  data() {
    return {
      friendShow: false,
      friendImg: "",
      friendName: "",
      websock: null,
      uuid: null,
      bottomBodyShow: false,
      content: "",
      messageRecord: [],
      roomId: "",
      redio:false
    };
  },
  mounted() {
    let roomId = this.$route.params.id;
    this.roomId = roomId;
    this.initWebSocket();
  },
  destroyed: function () {
    this.websocketclose();
  },
  beforeRouteEnter(to, from, next) {
    if (!Vue1.isOpen) {
      next("/");
    }
    next();
  },
  methods: {
    goRedio(){
       this.redio = true;
       this.$router.push("/chat/redio/1")
    },
    choiceImg() {
      this.$refs.filElem.dispatchEvent(new MouseEvent("click"));
    },
    getFile() {
      var that = this;
      const inputFile = this.$refs.filElem.files[0];
      if (inputFile) {
        if (
          inputFile.type !== "image/jpeg" &&
          inputFile.type !== "image/png" &&
          inputFile.type !== "image/gif"
        ) {
          alert("不是有效的图片文件！");
          return;
        }
        let param = new FormData(); //创建form对象
        param.append("file", inputFile); //通过append向form对象添加数据
        //console.log(param.get("file")); //FormData私有类对象，访问不到，可以通过get判断值是否传进去
        let config = {
          headers: { "Content-Type": "multipart/form-data" },
        }; //添加请求头
        this.$http
          .post("http://127.0.0.1:8080/upload", param, config)
          .then((response) => {
            console.log(response.data)
            if (response.data.flag != 200) {
              this.$message.error(response.data.message);
            } else {
              console.log(response);
              let data = {
                type: "img",
                content: response.data.data,
              };
              let dataJson = JSON.stringify(data);
              this.websocketsend(dataJson);
              this.bottomBodyShow = false;
              this.messageRecord.push({
                type:"img",
                sender: "me",
                content: response.data.data,
                imgUrl: this.$root.imageUrl,
                userName: this.$root.userName,
              });
              
            }
          })
          .catch((err) => {
            this.$message.error("上传失败");
            console.error(err);
          });
        // this.imgInfo = Object.assign({}, this.imgInfo, {
        //   name: inputFile.name,
        //   size: inputFile.size,
        //   lastModifiedDate: inputFile.lastModifiedDate.toLocaleString(),
        // });
        // const reader = new FileReader();
        // reader.readAsDataURL(inputFile);
        // reader.onload = function (e) {
        //   that.imgSrc = this.result;
        // };
      } else {
        return;
      }
    },
    bottomBodyGoShow() {
      this.bottomBodyShow = !this.bottomBodyShow;
    },
    initWebSocket() {
      //初始化weosocket
      //const wsuri = process.env.WS_API + this.$root.baseUrl+"/chat/0/0"; //ws地址
      if (this.roomId == null) {
        this.uuid = uuidv4().substring(0, 6);
        this.websock = new WebSocket(
          this.$root.socketUrl + "/" + 0 + "/" + this.uuid
        );
      } else {
        this.websock = new WebSocket(
          this.$root.socketUrl + "/" + 1 + "/" + this.roomId
        );
      }
      this.websock.onopen = this.websocketonopen;
      this.websock.onerror = this.websocketonerror;
      this.websock.onmessage = this.websocketonmessage;
      this.websock.onclose = this.websocketclose;
    },
    websocketonopen() {
      console.log("WebSocket连接成功");
    },
    websocketonerror(e) {
      //错误
      this.uuid = "网络错误";
      console.log("WebSocket连接发生错误");
    },
    websocketonmessage(e) {
      //数据接收
      const redata = JSON.parse(e.data);
      if (redata.type == "hello") {
        let data = {
          type: "hi",
          imgUrl: this.$root.imageUrl,
          name: this.$root.userName,
        };
        let jsonData = JSON.stringify(data);
        this.websocketsend(jsonData);
      } else if (redata.type == "hi") {
        this.friendImg = redata.imgUrl;
        this.friendName = redata.name;
        this.friendShow = true;
        console.log("------------");
        console.log(redata);
        console.log("------------");
      } else {
        console.log(redata);
        this.messageRecord.push({
          type: redata.type,
          sender: "friend",
          content: redata.content,
          imgUrl: this.friendImg,
          userName: this.friendName,
        });
      }

      // //但是点击某个列表时，会发送给后台一个标识，后台根据此标识返回相对应的数据，
      // //这个时候数据就只能从一个出口出，所以让后台加了一个键，例如键为1时，是每隔1秒推送的数据，为2时是发送标识后再推送的数据，以作区分
      // console.log(redata);
    },
    sendMessage() {
      let data = {
        type: "message",
        content: this.content,
      };
      let dataJson = JSON.stringify(data);

      this.websock.send(dataJson);
      this.messageRecord.push({
        sender: "me",
        content: this.content,
        imgUrl: this.$root.imageUrl,
        userName: this.$root.userName,
        type: "message"
      });
      this.content == "";
    },
    websocketsend(agentData) {
      //数据发送
      this.websock.send(agentData);
    },

    websocketclose(e) {
      //关闭
      console.log(e);
    },
  },
};
</script>
<style scoped>
.redio{
  position: fixed;
  z-index: 99;
  width: 100%;
  height: 100%;
  background: white;
  top: 0px;
  left: 0px;
}
.upload-file {
  visibility: hidden;
}
.body {
  width: 100%;
  height: 850px;
  max-height: 850px;
  overflow: scroll;
  overflow-x: hidden;
  background: url("https://521h.oss-cn-beijing.aliyuncs.com/font/1000.jpg?versionId=CAEQChiBgMCegcua2xciIDFiNmM4ZDMwZGYyNjQzNGFhMTJmMDdlOWVmNDM0Y2E0");
  background-position: center;
  background-size: contain;
  box-sizing: border-box;
  padding: 10px;
  padding-bottom: 51px;
}
.message {
  display: flex;
  justify-content: flex-start;
  margin: 10px 0px;
}
.message > div {
  box-sizing: border-box;
  text-align: left;
  padding: 4px;
  min-width: 30px;
  min-height: 100%;
  background: white;
  border-radius: 8px;
  /* line-height: 42px; */
  margin-left: 4px;
  font-size: 18px;
  max-width: 100%;
  height: auto;
  word-wrap: break-word;
  box-shadow: 0 2px 12px 0 rgb(255 255 255 / 45%);
}
.message > img {
  width: 50px;
  height: 50px;
  max-height: 50px;
  border-radius: 4px;
}
.message > img:nth-child(2){
  margin-left: 4px;
  width: 140px;
  height: auto;
  max-height: none;
}
.me > img:nth-child(2){
  margin-right: 4px;
  width: 140px;
  height: auto;
  max-height: none;
}
.me {
  flex-direction: row-reverse;
}
.me > div {
  margin-right: 4px;
}
.chat {
}
.head {
  width: 100%;
  height: 70px;
  line-height: 70px;
  font-weight: bold;
  font-size: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
}
.head img {
  height: 40px;
  width: 40px;
  border-radius: 4px;
}
.head .friend {
  align-items: center;
  display: flex;
  justify-content: center;
}
.bottom {
  position: fixed;
  bottom: 0px;
  left: 0px;
  width: 100%;

  background: #f6f7f7;
}
.bottom > .input {
  display: flex;
  height: 100%;
  justify-content: space-around;
  align-items: center;
  padding: 4px 4px;
  border-bottom: 1px solid grey;
  height: 50px;
}
.bottom > .body {
  position: fixed;
  width: 100%;
  display: flex;
  text-align: center;
  height: 100px;
  align-items: center;
  line-height: 100px;
  background: none;
  top: 54%;
  left: 0;
  justify-content: space-around;
}
.bottom > .body > div {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
  font-size: 30px;
  font-weight: bold;
  background: rgba(255, 255, 255, 0.575);
  width: 30%;
}
.bottom > .input > i {
  font-size: 25px;
  font-weight: bold;
  padding: 4px;
}
</style>